var hostname = 'http://phamtech.net/demo/infographic';
var canvases = [];
canvases.push(new fabric.Canvas('canvas'));
var canvas = canvases[0];
var number = 0;
var countCanvas = 1;
var link = '';
var copiedObject;
var copiedObjects = new Array();
var current;
var list = [];
var state = [];
var index = 0;
var index2 = 0;
var action = false;
var refresh = true;
canvas.on("object:added", function (e) {
    var object = e.target;
    console.log('object:modified');
    if (action === true) {
        state = [state[index2]];
        list = [list[index2]];
        action = false;
        console.log(state);
        index = 1;
    }
    object.saveState();
    console.log(object.originalState);
    state[index] = JSON.stringify(object.originalState);
    list[index] = object;
    index++;
    index2 = index - 1;
    refresh = true;
});
canvas.on("object:modified", function (e) {
    var object = e.target;
    console.log('object:modified');
    if (action === true) {
        state = [state[index2]];
        list = [list[index2]];
        action = false;
        console.log(state);
        index = 1;
    }

    object.saveState();
    state[index] = JSON.stringify(object.originalState);
    list[index] = object;
    index++;
    index2 = index - 1;
    console.log(state);
    refresh = true;
});
function bringToFront() {
    var activeObject = canvas.getActiveObject();
    if (activeObject) {
        canvas.bringToFront(activeObject);
    }
}
function sendToBack() {
    var activeObject = canvas.getActiveObject();
    if (activeObject) {
        canvas.sendToBack(activeObject);
    }
}
function bringForward() {
    var activeObject = canvas.getActiveObject();
    if (activeObject) {
        canvas.bringForward(activeObject);
    }
}
function sendBackwards() {
    var activeObject = canvas.getActiveObject();
    if (activeObject) {
        canvas.sendBackwards(activeObject);
    }
}
function addBackground(urlImage) {
    canvas.setBackgroundColor({
        source: urlImage,
        repeat: 'repeat',
    }, canvas.renderAll.bind(canvas));
}

function addTexts(text, font, size) {
    var random = getRandomLeftTop();
    var iText = new fabric.IText(text, {
        left: random['left'],
        top: random['top'],
        fontFamily: font,
        fontSize: size,
        fill: '#333',
        padding: 20,
        lockScalingX: true,
        lockScalingY: true
    });
    canvas.add(iText);
}
function toggleBold() {
    var activeObject = canvas.getActiveObject();
    setActiveStyle('fontWeight', getActiveStyle('fontWeight', activeObject) === 'bold' ? '' : 'bold', activeObject);
}
function toggleItalic() {
    var activeObject = canvas.getActiveObject();
    setActiveStyle('fontStyle', getActiveStyle('fontStyle', activeObject) === 'italic' ? '' : 'italic', activeObject);
}
function removeSelected() {
    var activeObject = canvas.getActiveObject(),
            activeGroup = canvas.getActiveGroup();
    if (activeGroup) {
        var objectsInGroup = activeGroup.getObjects();
        canvas.discardActiveGroup();
        objectsInGroup.forEach(function (object) {
            canvas.remove(object);
        });
    }
    else if (activeObject) {
        canvas.remove(activeObject);
    }
}
;
function cut() {
    var objectActive = canvas.getActiveObject();
    var objectAciveGroup = canvas.getActiveGroup();
    if (objectAciveGroup) {
        canvas.discardActiveGroup();
        for (var i in objectAciveGroup.objects) {
            var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
            object.set("top", objectAciveGroup.objects[i].top + 15);
            object.set("left", objectAciveGroup.objects[i].left + 15);
            copiedObjects[i] = object;
            canvas.remove(objectAciveGroup.objects[i]);
        }

    }
    else if (objectActive) {
        var object = fabric.util.object.clone(objectActive);
        object.set("top", objectActive.top + 15);
        object.set("left", objectActive.left + 15);
        copiedObject = object;
        copiedObjects = new Array();
        canvas.remove(objectActive);
    }
    canvas.renderAll();
}
function setActiveStyle(styleName, value, object) {
    object = object || canvas.getActiveObject();
    if (!object)
        return;
    if (object.setSelectionStyles && object.isEditing) {
        var style = {};
        style[styleName] = value;
        object.setSelectionStyles(style);
        object.setCoords();
    }
    else {
        object[styleName] = value;
    }

    object.setCoords();
    canvas.renderAll();
}
;
function selectAll() {
    var objs = canvas.getObjects().map(function (o) {
        return o.set('active', true);
    });
    var group = new fabric.Group(objs, {
        originX: 'center',
        originY: 'center'
    });
    canvas._activeObject = null;
    groupobjs = canvas.setActiveGroup(group.setCoords()).renderAll();
}
function undo() {
    if (index <= 0) {
        index = 0;
        return;
    }

    if (refresh === true) {
        index--;
        refresh = false;
    }

    console.log('undo');
    index2 = index - 1;
    current = list[index2];
    current.setOptions(JSON.parse(state[index2]));
    index--;
    current.setCoords();
    canvas.renderAll();
    action = true;
}

function redo() {
    action = true;
    if (index >= state.length - 1) {
        return;
    }

    console.log('redo');
    index2 = index + 1;
    current = list[index2];
    current.setOptions(JSON.parse(state[index2]));
    index++;
    current.setCoords();
    canvas.renderAll();
}
function copy() {
    var objectActive = canvas.getActiveObject();
    var objectAciveGroup = canvas.getActiveGroup();
    if (objectAciveGroup) {
        canvas.discardActiveGroup();
        for (var i in objectAciveGroup.objects) {
            var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
            object.set("top", objectAciveGroup.objects[i].top + 15);
            object.set("left", objectAciveGroup.objects[i].left + 15);
            copiedObjects[i] = object;
        }
    }
    else if (objectActive) {
        var object = fabric.util.object.clone(objectActive);
        object.set("top", objectActive.top + 15);
        object.set("left", objectActive.left + 15);
        copiedObject = object;
        copiedObjects = new Array();
    }
}
function align_left() {
    var width = canvas.getWidth();
    var height = canvas.getHeight();
    var objectActive = canvas.getActiveObject();
    var objectActiveGroup = canvas.getActiveGroup();
    if (objectActiveGroup) {
        var objectGroup = objectActiveGroup;
        objectGroup.set({
            top: height - objectActiveGroup.getHeight(),
            left: objectActiveGroup.getWidth()
        });
    } else if (objectActive) {
        var object = objectActive;
        object.set({
            top: height - objectActive.getHeight(),
            left: 0
        });
        canvas.add(object);
        canvas.remove(objectActive);
    }
    canvas.renderAll();
}
function paste() {
    if (copiedObjects.length > 0) {
        for (var i in copiedObjects) {
            canvas.add(copiedObjects[i]);
        }
    }
    else if (copiedObject) {
        canvas.add(copiedObject);
    }
    canvas.renderAll();
}
function addPhotos(urlImage) {
    fabric.util.loadImage(urlImage, function (img) {
        var object = new fabric.Image(img);
        object.set({
            left: 200,
            top: 150
        });
        canvas.add(object);
        canvas.renderAll();
    }, null, {crossOrigin: 'Anonymous'});

    canvas.renderAll();
}
;
function getActiveProp(name) {
    var object = canvas.getActiveObject();
    if (!object)
        return '';
    return object[name] || '';
}
function setActiveStyle(styleName, value, object) {
    object = object || canvas.getActiveObject();
    if (!object)
        return;
    if (object.setSelectionStyles && object.isEditing) {
        var style = {};
        style[styleName] = value;
        object.setSelectionStyles(style);
        object.setCoords();
    }
    else {
        object[styleName] = value;
    }

    object.setCoords();
    canvas.renderAll();
}
;
function setActiveProp(name, value) {
    var object = canvas.getActiveObject();
    if (!object)
        return;
    object.set(name, value).setCoords();
    canvas.renderAll();
}
function getActiveStyle(styleName, object) {
    object = object || canvas.getActiveObject();
    if (!object)
        return '';
    return (object.getSelectionStyles && object.isEditing)
            ? (object.getSelectionStyles()[styleName] || '')
            : (object[styleName] || '');
}
;
function addIcon(urlSvg) {
    var coord = getRandomLeftTop();
    fabric.loadSVGFromURL(urlSvg, function (objects, options) {
        var loadedObject = fabric.util.groupSVGElements(objects, options);

        loadedObject.set({
            left: 200,
            top: 300,
        })
                .setCoords();
        canvas.add(loadedObject);
    });
}

function downloadCanvas() {
    if (!fabric.Canvas.supports('toDataURL')) {
        alert('This browser doesn\'t provide means to serialize canvas to an image');
    }
    else {
        window.open(canvas.toDataURL('png'));
    }
}

function previewCanvas() {
    window.open(
            'data:image/svg+xml;utf8,' +
            encodeURIComponent(canvas.toSVG()));
}

function changeHeightCanvas() {
    canvas.setHeight(2000);
    canvas.setWidth(2000);
    canvas.renderAll();
}

/**SET UP**/
function getRandomLeftTop() {
    var offset = 50;
    return {
        left: fabric.util.getRandomInt(0 + offset, 700 - offset),
        top: fabric.util.getRandomInt(0 + offset, 500 - offset)
    };
}

function saveTemplate(id) {

    var data = JSON.stringify(canvas);

    $.ajax({
        url: hostname + '/admin/templates/edit/' + id,
        data: {
            action: 'saved',
            data: data,
            base64data: canvas.toDataURL('png')
        },
        type: 'post',
        success: function (response) {
            if (response == 'saved') {
                alert('Saved');
            } else {
                alert(response);
            }
        }
    });
}

function SecurityAccess(id, access, controller, group_id) {

    $.ajax({
        url: hostname + '/admin/' + controller + '/security/' + group_id,
        data: {
            action: 'security',
            id: id,
            access: access
        },
        type: 'post',
        success: function (response) {

        }
    });
}

function ShowModel(id) {

    $.ajax({
        url: hostname + '/admin/templates/modal',
        data: {
            action: 'modal',
            id: id
        },
        type: 'post',
        success: function (response) {
            var categories = JSON.parse(response);
            var select = "<select class='form-control' multiple id='categories' name='categories'>";
            for (var x in categories) {
                select += "<option value='" + x + "'>" + categories[x] + "</option>";
            }
            select += "</select>";
            if (id !== 'undefined') {
                select += "<input type='hidden' value='" + id + "' id='id_copy'/>";
            }
            $('#result').html(select);
            $('#modal').modal('show');
        }
    });
}

function Upgrade(id) {

    $.ajax({
        url: hostname + '/admin/customers/upgrade',
        data: {
            action: 'upgrade',
            id: id
        },
        type: 'post',
        success: function (response) {
            var subscriptions = JSON.parse(response);
            var select = "<select class='form-control' id='subscription' name='subscription'>";
            for (var x in subscriptions) {
                select += "<option value='" + x + "'>" + subscriptions[x] + "</option>";
            }
            select += "</select>";
            if (id !== 'undefined') {
                select += "<input type='hidden' value='" + id + "' id='id_customer'/>";
            }
            $('#result').html(select);
            $('#upgrade').modal('show');
        }
    });
}

function NewTemplate() {
    var name = $("#name").val();
    var categories = $("#categories").val();
    var id_copy = $("#id_copy").val();

    if (id_copy !== 'undefined') {
        id = id_copy;
    } else {
        id = '';
    }

    $.ajax({
        url: hostname + '/admin/templates/add',
        data: {
            action: 'new_template',
            name: name,
            categories: categories,
            id_copy: id
        },
        type: 'post',
        success: function (response) {
            if (response) {
                window.location = hostname + '/admin/templates/app/' + response;
            }
        }
    });
}
function changeWidthCanvas() {
    var w = $('#canwidth').val();
    if (isNaN(w) || w > 5000) {
        alert("Size is wrong");
        return;
    }
    else {
        var newWidth = $('#canwidth').val() / $('canvas').width();
        if ($("#checkResize").prop('checked', true)) {
            for (var i = 0; i < canvases.length; i++) {
                if (canvases[i] != null) {
                    canvas = canvases[i];
                    selectAll(); //select all object

                    var objectActive = canvas.getActiveObject(); //object
                    var objectAciveGroup = canvas.getActiveGroup(); //objects
                    if (objectAciveGroup) {
                        var objectsInGroup = objectAciveGroup.getObjects();
                        canvas.discardActiveGroup();
                        objectsInGroup.forEach(function (object) {
                            if ((object.get('type') == 'i-text')) {
                                fonsize = object.get('fontSize') * newWidth;
                                setActiveStyle('fontSize', fonsize, object);
                                object.set({top: objTop,
                                    left: objLeft * newWidth});
                            }
                            else {
                                objTop = object.getTop();
                                objLeft = object.getLeft();
                                objWidth = object.getWidth();
                                objHeight = object.getHeight();
                                object.setWidth(objWidth * newWidth);
                                object.setHeight(objHeight * newWidth);
                                object.set({top: objTop,
                                    left: objLeft * newWidth});
                            }

                        });
                    }
                    else {
                        objTop = objectActive.getTop();
                        objLeft = objectActive.getLeft();
                        objWidth = objectActive.getWidth();
                        objHeight = objectActive.getHeight();
                        objectActive.setWidth(objWidth * newWidth);
                        objectActive.setHeight(objHeight * newWidth);
                        objectActive.set({top: objTop,
                            left: objLeft * newWidth});
                    }
                }

                if (w > canvas.getWidth()) {
                    canvas.setHeight(w * 0.25 + canvas.getHeight());
                }
                else {
                    canvas.setHeight(canvas.getHeight() - w * 0.25);
                }
                canvas.setWidth(w);
                canvas.calcOffset();
                canvas.renderAll();
            }
        }
        else {
            for (var i = 0; i < canvases.length; i++) {
                if (canvases[i] != null) {
                    canvas = canvases[i];
                    if (w > canvas.getWidth()) {
                        canvas.setHeight(w * 0.25 + canvas.getHeight());
                    }
                    else {
                        canvas.setHeight(canvas.getHeight() - w * 0.25);
                    }
                    canvas.setWidth(w);
                    canvas.calcOffset();
                    canvas.renderAll();
                }
            }
        }

    }

}
function changeHeightCanvas() {
    var h = $('#canheight').val();
    if (isNaN(h) || h > 2000) {
        alert("Size is wrong");
    }
    else {
        var newHeight = $('#canheight').val() / $('canvas').height();
        // canvas.setHeight($("#canheight").val());
        if ($("#checkResize").prop('checked', true)) {

            selectAll(); //select all object

            var objectActive = canvas.getActiveObject(); //object
            var objectAciveGroup = canvas.getActiveGroup(); //objects
            if (objectAciveGroup) {
                var objectsInGroup = objectAciveGroup.getObjects();
                canvas.discardActiveGroup();
                objectsInGroup.forEach(function (object) {
                    if ((object.get('type') == 'i-text')) {
                        fonsize = object.get('fontSize');
                        setActiveStyle('fontSize', fonsize * newWidth, object);
                    }
                    else {
                        objTop = object.getTop();
                        objLeft = object.getLeft();
                        objWidth = object.getWidth();
                        objHeight = object.getHeight();
                        object.setWidth(objWidth * newHeight);
                        object.setHeight(objHeight * 0.5 * newHeight);
                        object.set({top: objTop * newHeight,
                            left: objLeft});
                    }

                });
            }
            else {
                objTop = objectActive.getTop();
                objLeft = objectActive.getLeft();
                objWidth = objectActive.getWidth();
                objHeight = objectActive.getHeight();
                objectActive.setWidth(objWidth * 0.5 * newHeight);
                objectActive.setHeight(objHeight * newHeight);
                objectActive.set({top: objTop * newHeight,
                    left: objLeft});
            }
        }
        if (h > canvas.getHeight()) {
            canvas.setWidth(h * 0.25 + canvas.getWidth());
        }
        else {
            canvas.setWidth(canvas.getHeight() - h * 0.25);
        }
        canvas.setHeight(h);
        canvas.calcOffset();
        canvas.renderAll();
    }

}
function getLockX() {
    return getActiveProp('lockMovementX');
}

function getLockY() {
    return getActiveProp('lockMovementY');
}

function setLockX(valuex, valuey) {
    setActiveProp('lockMovementX', valuex);
    setActiveProp('lockMovementY', valuey);
    setActiveProp('lockScalingX', valuey);
    setActiveProp('lockScalingY', valuey);
    setActiveProp('lockRotation', valuey);
}



$(document).ready(function () {

    canvas.on('mouse:down', function (options) {
        var objectActive = canvas.getActiveObject();
        if (objectActive) {
            if (typeof (objectActive.link) != 'undefined') {
                if (objectActive.link != '') {
                    $('.link-icon').addClass('link-active');
                    return;
                }
            }
        }

        $('.link-active').removeClass('link-active');
    });
    $('.link-icon').click(function () {
        var objectActive = canvas.getActiveObject();
        var activeGroup = canvas.getActiveGroup();
        if (activeGroup) {
            if (confirm('More than one object will be set with the hyperlink, Are you sure?')) {
                link = prompt('Set hyperlink to object:', 'http://');
                if (link == 'http://')
                    return;
                var objectInGroup = activeGroup.getObjects();
                objectInGroup.forEach(function (obj) {
                    obj.set('link', link);
                });
                $(this).addClass('link-active');
            }
        } else if (objectActive) {
            link = prompt('Set hyperlink to object:', objectActive.link || 'http://');
            if (link == 'http://')
                return;
            objectActive.set('link', link);
            $(this).addClass('link-active');
        } else {
            alert('You must chose 1 object');
        }

    });
    $('.down-icon').click(function () {
        if (number === canvases.length - 1) {
            alert("Can't move down canvas");
            return;
        }
        if (number !== false) {
            var canvasTem = JSON.stringify(canvas);
            var numberTem = number + 1;
            while (numberTem <= canvases.length) {
                if (canvases[numberTem] == null) {
                    numberTem++;
                } else {
                    break;
                }
            }

            if (numberTem >= canvases.length) {
                alert("You can't move down canvas");
                return;
            }

            canvas.loadFromJSON(JSON.stringify(canvases[numberTem]));
            canvases[numberTem].loadFromJSON(canvasTem);
        } else {
            alert('You must chose 1 block');
        }
    });
    $('.up-icon').click(function () {
        if (number === 0) {
            alert("Can't move up canvas");
            return;
        }
        if (number !== false) {
            var canvasTem = JSON.stringify(canvas);
            var numberTem = number - 1;
            while (numberTem >= -1) {
                if (canvases[numberTem] == null) {
                    numberTem--;
                } else {
                    break;
                }
            }

            if (numberTem == -1) {
                alert("You can't move up canvas");
                return;
            }
            canvas.loadFromJSON(JSON.stringify(canvases[numberTem]));
            canvases[numberTem].loadFromJSON(canvasTem);
        } else {
            alert('You must chose 1 block');
        }
    });
    var canvasId = 0;
    $(".add-icon").click(function (e) {
        e.preventDefault();
        canvasId++;
        var newCanvas = $('<canvas id="canvas-' + canvasId + '" width=800 height=400></canvas>');
        $('.container_canvas').append(newCanvas);
        var newCanvas = new fabric.Canvas('canvas-' + canvasId);
        newCanvas.backgroundColor = '#fff';
        canvases.push(newCanvas);
        countCanvas++;
    });
    $('canvas').hover(
            function () {
                // console.log(1);
                $(this).addClass('active');
            },
            function () {
                $('.active').removeClass('active');
            }

    );
    $('body').delegate('.upper-canvas', 'click', function () {
        var myCanvas = $(this).parent().find(' canvas:first').attr('id');
        var intID = myCanvas.replace("canvas-", "0");
        number = parseInt(intID);
        if (isNaN(number)) {
            number = 0;
        }

        canvas = canvases[number];
        canvas.calcOffset();
        canvas.renderAll();
        $('.unactive').removeClass('unactive');
    });
    $('body').delegate('.upper-canvas', 'mouseover', function () {
        var myCanvasId = $(this).parent().find('canvas:first').attr('id');
        var strNumber = myCanvasId.replace('canvas-', '0');
        var idNumber = parseInt(strNumber);
        var _this;
        if (isNaN(idNumber)) {
            _this = $('#canvas');
            idNumber = 0;
        } else {
            _this = $('#canvas-' + idNumber);
        }

        if (idNumber == number)
            return;
        _this = _this.parent().find('.upper-canvas');
        _this.addClass('unactive');
        _this.addClass('active');
    });
    $('body').delegate('.upper-canvas', 'mouseout', function () {
        $('.unactive').removeClass('unactive');
        $('.active').removeClass('active');
    });
    $('.delete-icon').click(function () {
        if (countCanvas === 1) {
            alert("Can't remove last canvas !");
            return;
        }
        var elementDelete;
        if (number !== false) {
            if (number == 0) {
                elementDelete = $('#canvas').parent();
            } else {
                elementDelete = $('#canvas-' + number).parent();
            }
            elementDelete.remove();
            canvases[number] = null;
            countCanvas--;
            number = false;
        } else {
            alert('You must select a block');
        }
    });
    $(".clone-icon").click(function (e) {
        e.preventDefault();
        canvasId++;
        var newCanvas = $('<canvas id="canvas-' + canvasId + '" width=800 height=400></canvas>');
        $('.container_canvas').append(newCanvas);
        var cloneCanvas = new fabric.Canvas('canvas-' + canvasId);
        selectAll();
        var backGround = canvas.backgroundColor;
        cloneCanvas.backgroundColor = backGround;
        var objectActive = canvas.getActiveObject();
        var objectAciveGroup = canvas.getActiveGroup();
        if (objectAciveGroup) {
            canvas.discardActiveGroup();
            for (var i in objectAciveGroup.objects) {
                var object = fabric.util.object.clone(objectAciveGroup.objects[i]);
                object.set("top", objectAciveGroup.objects[i].top);
                object.set("left", objectAciveGroup.objects[i].left);
                cloneCanvas.add(object);
            }
        }
        else if (objectActive) {
            var object = fabric.util.object.clone(objectActive);
            object.set("top", objectActive.top);
            object.set("left", objectActive.left);
            cloneCanvas.add(object);
        }
        canvases.push(cloneCanvas);
        countCanvas++;
    });
});
$('#canvas').ready(function (e) {
    var ctrl = false;
    $(document).keydown(function (e) {
        if (e.code == 127) {
            return;
        }

        if (e.which == 46) {
            removeSelected();
        }

        if (e.which == 17)
            ctrl = true;
        if (e.which == 65 || e.which == 97) {
            if (ctrl) {
                selectAll();
            }
        }

        if (e.which == 88 || e.which == 120) { // ctr + x
            if (ctrl) {
                cut();
            }
        }

        if (e.which == 67 || e.which == 99) {   //ctr + c
            if (ctrl) {
                copy();
            }
        }

        if (e.which == 86 || e.which == 118) {   //ctr + v
            if (ctrl) {
                paste();
            }
        }

        if (e.which == 90 || e.which == 122) {   //ctr + z
            if (ctrl) {
                undo();
            }
        }
    });
});





function alignText(value) {
    setActiveProp('textAlign', value.toLowerCase());
}


$(document).ready(function () {
    var url = window.location.href;
    if (url.indexOf('app') !== -1) {
        var id = url.substring(url.lastIndexOf('/') + 1);
        $.ajax({
            url: hostname + '/admin/templates/get',
            data: {
                action: 'get',
                id: id,
            },
            type: 'post',
            success: function (response) {
                if (response !== '0') {
                    canvas.loadFromJSON(response, canvas.renderAll.bind(canvas));
                } else {
                    window.location = hostname + '/admin/templates/';
                }
            }
        });
    }
});

//---------------------------14/10--------------------------------------
$(document).ready(function () {
    $('#font-family').change(function () {
        var str = $(this).find('option:selected').text();
        setActiveStyle('fontFamily', str);
    });

    $('#font-size').change(function () {
        var str = $(this).find('option:selected').text();
        setActiveStyle('fontSize', str);
    });

    $('#colorSelector').ColorPicker({
        color: '#0000ff',
        onShow: function (colpkr) {
            $(colpkr).fadeIn(500);
            return false;
        },
        onHide: function (colpkr) {
            $(colpkr).fadeOut(500);
            return false;
        },
        onChange: function (hsb, hex, rgb) {
            setActiveStyle('fill', '#' + hex);
        }
    });
 $('.opacity').click(function(){
       $('#wrap-slider').toggle();
    });
    $("#slider").slider({
        range: "min",
        min: 1,
        max: 100,
        value: 100,
        slide: function (event, ui) {
            var value = ui.value;
            setActiveStyle('opacity', parseInt(value, 10) / 100);
        }
    });
    
});


